#!/bin/bash 

# NOTE: set the path to SVDFeature
SVDFEATURE=../../svdfeature-gfmf
#----------------------------

set -e
rm -f log.txt

testbuf=`python ../../python/extract_conf.py $conf test:buffer_feature`
trainbuf=`python ../../python/extract_conf.py $conf buffer_feature`
# echo "train_buffer: $trainbuf"

if [ ! -e "$trainbuf" ]; then
	echo "train buffer $trainbuf doesn't exist"
	exit 1
fi

if [ ! -e "$testbuf" ]; then
	echo "test buffer $testbuf doesn't exist"
	exit 1
fi

if [ ! -n "$user_label" ]; then
	user_label=../../user.empty.labels
fi

echo "user_label: $user_label"

if [ ! -n "$ap_k" ]; then
	ap_k=3
fi

if [ ! -n "$check_save" ]; then
	check_save=1
fi

if [ ! -n "$post_view" ]; then
	post_view=0
fi

if [ ! -n "$eval_offset" ]; then
	eval_offset=1
fi

if [ ! -n "$save_pred" ]; then
	save_pred=0
fi

if [ ! -n "$show_loss" ]; then
	show_loss=0
fi

if [ ! -n "$svd_seed" ]; then
	svd_seed=10
fi

if [ -n "$init_model" ]; then
	cp $init_model `printf %04d $start`.model
fi
#----------- training & testing -------------

for (( i=$start; i < $nround; i ++ ))
do
	echo "training round $i ..."
	# run training, use different seed to ensure different kinds of pos/neg pair in each round
	# train i --> i+1
	$SVDFEATURE/solvers/gfmf/svdf_gfmf $conf max_round=1 num_round=$nround start_counter=$i continue=1 silent=0  seed=$((i+svd_seed))

	touch stats.txt
	if [ $evaltest -ne 0 ]
	then
        # infer i+1
	    $SVDFEATURE/solvers/gfmf/svdf_gfmf_infer $conf pred=$((i+eval_offset)) name_pred=pred.txt silent=1 > stats.txt 

		if [ $show_loss -eq 1 ]; then
			echo "testing average loss" >> stats.txt
			~/code/svd-feature/solvers/gfmf/svdf_gfmf_infer $conf pred_loss=$((i+eval_offset)) test:buffer_feature=$testbuf test:input_type=2 test:rank_sample_num=20 silent=1 seed=$((i+svd_seed)) >> stats.txt
		fi

		if [ ! `python ../../python/check_pred_save.py $conf $i` -eq 0 ]; then
			cp pred.txt "pred.$i.txt"
		fi
        ../../eval-cpp/evalKDDMAP ../../test.group.imfb ../../test.group.rate pred.txt $((i+1)) 3 >> stats.txt
	fi
	
	# record results in log
	cat stats.txt
	echo "training round $i ..." | cat >> log.txt
	cat stats.txt >> log.txt
	rm -f stats.txt pred.txt pred_train.txt
	# check whether we want to keep the model of this round
	if [[ $check_save -eq 1 &&  `python ../../python/check_model_save.py $conf $i` -eq 0 ]]
	then
		rm `printf %04d $i`.model
	fi
done
